import React from 'react';
import { ModalForm, ProFormText } from '@ant-design/pro-form';
import { message } from 'antd';
import { changePwd } from '@/services/login';

export default (props) => {
  const { visible, onVisibleChange } = props;

  const onFinish = async (values) => {
    const result = await changePwd(values);
    if (result.success) {
      message.success('修改密码成功');
    } else if (result.message) {
      message.error(result.message);
    }
    return result.success;
  };

  return (
    <ModalForm
      title="修改密码"
      width={500}
      visible={visible}
      onVisibleChange={onVisibleChange}
      onFinish={onFinish}
      validateTrigger="onBlur"
      layout="horizontal"
      labelCol={{ span: 5 }}
      wrapperCol={{ span: 24 }}
    >
      <ProFormText.Password
        name="oldPwd"
        label="原密码"
        rules={[
          {
            required: true,
            message: '请输入原密码',
          },
        ]}
      />
      <ProFormText.Password
        name="newPwd"
        label="新密码"
        placeholder="密码限长为6-20位"
        rules={[
          {
            required: true,
            message: '请输入新密码',
          },
          {
            whitespace: true,
            message: '密码不能是空白',
          },
          {
            min: 6,
            max: 20,
            message: '密码限长为6-20位',
          },
        ]}
      />
      <ProFormText.Password
        name="confirmPwd"
        label="确认密码"
        placeholder="密码限长为6-20位"
        rules={[
          {
            required: true,
            message: '请输入确认密码',
          },
          ({ getFieldValue }) => ({
            validator: (_, value) => {
              const newPwd = getFieldValue('newPwd');
              if (!value || !newPwd || newPwd === value) {
                return Promise.resolve();
              }
              return Promise.reject();
            },
            message: '两次输入密码不一致',
          }),
        ]}
      />
    </ModalForm>
  );
};
